import React, { useEffect, useState } from 'react'
import { Modal, message, Skeleton } from 'antd'
import ProForm, { ProFormText } from '@ant-design/pro-form'
import { updateUser, showUser, addUser } from '@/services/user' 


export default function CreateOrEdit(props) {

  const { isModalVisible, isShowModal, actionRef, editId } = props

  // 状态改变 驱动 视图更新
  let [initialValues, setInitialValues] = useState(undefined)

  const type = editId === undefined ? '添加' : '编辑'

  useEffect(async () => {
    // 获取用户详情
    if(editId !== undefined) {
      const response = await showUser(editId)
      setInitialValues({
        name: response.name,
        email: response.email
      })
    }
  }, [])

  // 处理表单提交
  const handleSubmit = async values => {
    let response = undefined
    if(editId === undefined) {
      // 添加
      response = await addUser(values)
    } else {
      // 编辑
      response = await updateUser(editId, values)
    }
    if(response.status === undefined) {
      message.success(`${type}用户成功!`)
      // 刷新表格
      actionRef.current.reload()
      isShowModal(false)
    }
  }

  return (
    <Modal title={`${type}用户`} visible={isModalVisible} onCancel={() => {isShowModal(false)}} footer={null} destroyOnClose={true}>
      {
        initialValues === undefined && editId !== undefined ? 

        <Skeleton active paragraph={{ rows: 4 }} /> :

        <ProForm
          onFinish={ (values) => handleSubmit(values) }
          initialValues={ initialValues }
        >
          <ProFormText
            name="name"
            label="昵称"
            placeholder="请输入昵称"
            rules={[
              { required: true, message: '请输入昵称!' }
            ]}
          />
          <ProFormText
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '邮箱格式不正确!' }
            ]}
          />
          {
            editId !== undefined ? '' : 
            <ProFormText.Password
              name="password"
              label="密码"
              placeholder="请输入密码"
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 6, message: '密码最少6位!' }
              ]}
            />
          }
        </ProForm>
      }
    </Modal>
  )
}
